package cn.itcast.model.statistics

import cn.itcast.model.base.BaseModel
import org.apache.spark.sql.DataFrame
import org.apache.spark.sql.expressions.Window

object PayMethodModel extends BaseModel{
  override def setAppName(): String = "PayMethodModel"

  override def importSparkEnv(): Unit = {}
  import spark.implicits._
  import org.apache.spark.sql.functions._
  override def setTagId(): Int = 412

  override def computeTag(fiveRuleDF: DataFrame, hbaseSource: DataFrame): DataFrame = {
    // 将5级规则数据转换为Map.
    val fiveMap: Map[String, String] = fiveRuleDF.map(row => {
      val id: String = row.getAs[Int]("id").toString
      val rule: String = row.getAs[String]("rule").toString
      (rule, id)
  }).collect().toMap
    // 重点,就是找到用户常用的支付方式.
    val getTag = udf((paymentCode: String) => {
      //从5级规则map中获取对应的标签ID
      fiveMap.getOrElse(paymentCode, fiveMap.getOrElse("otherpay", ""))
    })
    // 先对数据进行分组: 用户ID和支付方式作为分组条件
    hbaseSource.groupBy('memberId, 'paymentCode)
      .agg(count('paymentCode).as("num"))
      //      .show()
      //+--------+-----------+---+
      //|memberId|paymentCode|num|
      //+--------+-----------+---+
      //|13823481|     alipay| 96|
      //| 4035297|     alipay| 80|
      .withColumn(
      //列名
      "rn",
      //当前列的值: 按照用户ID进行分组,根据支付方式的数量进行排名
      row_number().over(Window.partitionBy('memberId).orderBy('num.desc))
    )
      //      .show()
      //+---------+-----------+---+---+
      //| memberId|paymentCode|num| rn|
      //+---------+-----------+---+---+
      //| 13822725|     alipay| 89|  1|
      //| 13822725|        cod| 12|  2|
      //| 13822725|     kjtpay|  9|  3|
      .where("rn = 1")
      //获取数据,打标签
      .select('memberId.as("userId"), getTag('paymentCode).as("tagIds"))
    //      .show()
    //+---------+------+
    //|   userId|tagIds|
    //+---------+------+
    //| 13822725|   114|
    //| 13823083|   114|
    //|138230919|   114|
  }
  def main(args: Array[String]): Unit = {
    val frame: DataFrame = executeModel()
    saveData(frame)
  }
}

